import sys

import numpy as np
from Individual import *

modeNum = 0


def geneAct(actNum, pop_size, actList):
    """

    :param actNum:
    :param pop_size:
    :param actList:
    :return:
    """
    actStr = np.arange(1, actNum + 1).tolist()
    np.random.shuffle(actStr)
    actStr = fixActOrder(actStr, actList)
    return actStr


def fixActOrder(old, actList):
    """

    :param old:
    :param actNum:
    :param actList:
    :return:
    """
    actNum = len(actList)
    order = [1]
    old.remove(1)
    while len(order) < actNum:
        for i in old:
            # 检查当前活动的紧前活动是否全部加入到order中，下方表达式为前面是否为后面的子集
            if set(actList[i].preList) <= set(order):
                order.append(i)
                old.remove(i)
                break
    return order


def fixModeOrder(modeStr, actStr, actList, resources):
    """
    有模式的资源需求超过资源可用量
    :param modeStr:
    :param actStr:
    :param actList:
    :return:
    """
    # print("actStr :", actStr)
    # print("modeStr:", modeStr)
    # for i in range(1, 13):
    #     print(actList[i].modes)
    res = resources.copy()
    res = np.array(res)
    for i in range(1, len(modeStr) - 1):
        # print(modeStr[i])
        # print(modeStr[i]-1)
        # print(actList[i])
        # print(actList[actStr[i]].modes[modeStr[actStr[i]]])
        # print("***************************************************")
        while (actList[actStr[i]].modes[modeStr[i]][1:] > res).any():
            # print(i)
            # print("old: ", modeStr[i])
            # print(actList[actStr[i]].modes[modeStr[i]][1:])
            # print("------------------------------")
            modeStr[i] = np.random.randint(1, 4)
            # print("new: ", modeStr[i])
            # print(actList[actStr[i]].modes[modeStr[i]][1:])
    # print("modeStr:", modeStr)
    return modeStr


modeNum = 3


def geneMode(actNum, actStr, actList, resources):
    temp = np.random.randint(1, modeNum + 1, actNum - 2)
    modeStr = [1]
    for item in temp:
        modeStr.append(item)
    modeStr.append(1)
    modeStr = fixModeOrder(modeStr, actStr, actList, resources)
    return modeStr


def encode(modenum, pop_size, actNum, actList, resourceNum, resources, inCreasedCost):
    """
    生成初始种群编码
    :param pop_size:
    :param actNum:
    :param actList:
    :param resourceNum:
    :param resources:
    :return:
    """
    global modeNum
    modeNum = modenum
    pop = []
    for i in range(0, pop_size):
        actStr = geneAct(actNum, 2, actList, )
        modeStr = geneMode(actNum, actStr, actList, resources)
        indiv = Individual(actStr, modeStr)
        indiv.resources = resources.copy()
        indiv.increasedCost = inCreasedCost.copy()
        # print(indiv.resources)
        pop.append(indiv)

    return pop.copy()


if __name__ == '__main__':
    geneAct(12, 2)
    geneMode(12)
